package com.letao.server.utils;

import com.aliyun.oss.OSS;
import com.letao.server.config.OSSConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * OSS处理类
 */
@Component
public class OSSUtils {
    @Autowired
    private OSS ossClient;

    @Autowired
    private OSSConfig ossConfig;

    /**
     * @param file 需要上传的文件
     * @param use  文件用途
     * @param name 文件名
     * @return 图片访问路径
     * @throws IOException 抛出的异常
     */
    public String update(MultipartFile file, String use, String name) throws IOException {
        // 获取OSS配置信息
        String endpoint = ossConfig.getEndpoint();
        String bucketName = ossConfig.getBucketName();

        // 获取文件流
        InputStream inputStream = file.getInputStream();
        // 获取文件本名
        String originalFilename = file.getOriginalFilename();
        // 拼接文件上传名
        String fullname = use + "/" + name + originalFilename.substring(originalFilename.lastIndexOf("."));

        // 上传文件
        ossClient.putObject(bucketName, fullname, inputStream);

        // 拼接返回路径
        String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + fullname;
        return url;
    }

    public Boolean delete(String url) {
        Boolean flag = false;
        String name = url.substring(ossConfig.host.length());
        try {
            ossClient.deleteObject(ossConfig.getBucketName(), name);
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }
}
